//
//  JXForgetPwdController.m
//  JiaoX
//
//  Created by jiaoxiu－005 on 15/1/9.
//  Copyright (c) 2015年 北京娇羞科技有限公司. All rights reserved.
//  重设密码

#import "JXForgetPwdController.h"
#import "JXBaseResponse.h"
#import "JXBaseRequest.h"
#import "SelfDataTool.h"
#import "JXNavigationController.h"
#import "TimeUtils.h"

#define  Edit_Width JXScreenW-JXPublicInset*2
#define  Edit_Height 46.5


@interface JXForgetPwdController ()<UIScrollViewDelegate>
{
    NSTimer *_countDownTimer;
    int time;
}
@property(nonatomic,strong)  UIScrollView *scrollView;
@property(nonatomic,strong)  UITextField *phoneCode;
@property(nonatomic,strong)  UITextField *validateCode;
@property(nonatomic,strong)  UITextField *password;
@property(nonatomic,strong)  UIButton *enterModify;
@property(nonatomic,strong)  UIButton *sendCodeBtn;


@end

@implementation JXForgetPwdController

- (void)viewDidLoad {
    [super viewDidLoad];
    time = 60;
    self.navigationItem.title = @"重设密码";
    [self.view setBackgroundColor:[UIColor whiteColor]];
    //添加阻尼效果
    UIScrollView *scrollView = [[UIScrollView alloc]init];
    scrollView.frame = CGRectMake(0, 0, JXScreenW, self.view.height);
    [scrollView setContentSize:CGSizeMake(JXScreenW, self.view.height)];
    scrollView.showsVerticalScrollIndicator = FALSE;
    scrollView.showsHorizontalScrollIndicator = FALSE;
    scrollView.delegate = self;
    self.scrollView = scrollView;
    [self.view addSubview:scrollView];
    //初始化手机号输入框
    [self initPhoneCodeTextField];
    //初始化验证码输入框
    [self initValidateCodeTextField];
    //初始化新密码输入框
    [self initNewPasswordTextField];
    //确认修改按钮
    [self initEnterModifyButton];
    //发送验证码按钮
    [self initSendCodeBtn];
}

/**
 *  重写scrollview的滚动方法隐藏软件盘，结束输入,成为scrollview的代理才可以使用这个方法
 *
 *  @param scrollView
 */
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

/**
 *初始化手机号输入框
 */
-(void)initPhoneCodeTextField{
    UITextField *phoneCode = [[UITextField alloc]init];
    //frame
    CGFloat phoneCodeX = JXPublicInset;
    CGFloat phoneCodeY = 20;
    CGRect rect =  CGRectMake(phoneCodeX, phoneCodeY, Edit_Width, Edit_Height);
    [self initTextField:self.scrollView edit:phoneCode frame:rect placeholderText:@"手机号"];
    phoneCode.keyboardType = UIKeyboardTypePhonePad;
    phoneCode.clearButtonMode = UITextFieldViewModeNever;//设置不要在显示叉号
    self.phoneCode = phoneCode;
}
/**
 *  初始化发送验证码
 */
-(void)initSendCodeBtn
{
    NSString *sendCodeTitle = @"发送验证码";
    _sendCodeBtn=[[UIButton alloc]init];
    [_sendCodeBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [_sendCodeBtn setTitle:sendCodeTitle forState:UIControlStateNormal];
    [_sendCodeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_sendCodeBtn setContentMode:UIViewContentModeCenter];
    [_sendCodeBtn setFrame:CGRectMake(CGRectGetMaxX(self.phoneCode.frame)-self.phoneCode.width/4 - JXPublicInset*2, (CGRectGetMinY(self.phoneCode.frame)+self.phoneCode.height-15)/2, self.phoneCode.width/4 + JXPublicInset, self.phoneCode.height-15)];
    [_sendCodeBtn setBackgroundImage:[UIImage resizedImage:@"btn_login_bg"] forState:UIControlStateNormal];
    [_sendCodeBtn addTarget:self action:@selector(sendCode) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:_sendCodeBtn];
}

/**
 *初始化验证码输入框
 */
-(void)initValidateCodeTextField{
    UITextField *validateCode = [[UITextField alloc]init];
    //frame
    validateCode.keyboardType = UIKeyboardTypeNumberPad;
    CGRect rect =  CGRectMake(JXPublicInset, CGRectGetMaxY(self.phoneCode.frame)+10,Edit_Width, Edit_Height);
    [self initTextField:self.scrollView edit:validateCode frame:rect placeholderText:@"验证码"];
    self.validateCode = validateCode;
}

/**
 *初始化新密码输入框
 */
-(void)initNewPasswordTextField{
    UITextField *newPassword = [[UITextField alloc]init];
    //frame
    newPassword.secureTextEntry = YES;
    CGRect rect =  CGRectMake(JXPublicInset, CGRectGetMaxY(self.validateCode.frame)+10,Edit_Width, Edit_Height);
    [self initTextField:self.scrollView edit:newPassword frame:rect placeholderText:@"新密码"];
    self.password = newPassword;
}

/**
 *初始化确认修改按钮
 */
-(void)initEnterModifyButton{
    UIButton *enterModify =[[UIButton alloc]init];
    [enterModify setTitle:@"确认修改" forState:UIControlStateNormal];
    [enterModify setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [enterModify setContentMode:UIViewContentModeCenter];
     enterModify.frame = CGRectMake(JXPublicInset, CGRectGetMaxY(self.password.frame)+10, Edit_Width,  Edit_Height);
    [enterModify setBackgroundImage:[UIImage resizedImage:@"btn_login_bg"] forState:UIControlStateNormal];
    [enterModify addTarget:self action:@selector(enter) forControlEvents:UIControlEventTouchUpInside];
     self.enterModify = enterModify;
    [self.scrollView addSubview:enterModify];
}

/**
 *  初始化输入框
 *
 *  @param container 容器
 *  @param edit 输入框
 *  @param frame  frame
 *  @param placeholderText  默认显示文字
 */
-(void)initTextField :(UIView *)container edit:(UITextField *)edit frame:(CGRect)frame placeholderText:(NSString *)placeholderText{
    //设置边框
    [edit.layer setBorderColor:JXColor(204, 204, 204).CGColor];
    [edit.layer setBorderWidth:0.7];
    [edit.layer setCornerRadius:5];
    
    edit.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    edit.attributedPlaceholder =[[NSAttributedString alloc] initWithString:placeholderText attributes:@{NSForegroundColorAttributeName: JXColor(204, 204, 204)}];
    edit.frame = frame;
    edit.clearButtonMode = UITextFieldViewModeAlways;
    [self textFieldAddleftView:edit];
    [container addSubview:edit];
}

/**
 *  输入框左边增加左边距
 *
 *  @param edit
 */
-(void)textFieldAddleftView:(UITextField *)edit{
    //添加左边距
    CGRect frame = [edit frame];
    frame.size.width = 7.0f;
    UIView *leftview = [[UIView alloc] initWithFrame:frame];
    edit.leftViewMode = UITextFieldViewModeAlways;
    edit.leftView = leftview;
}

/**
 *  确认修改
 */
-(void) enter{
    NSString *phoneCode = self.phoneCode.text;
    NSString *validCode = self.validateCode.text;
    NSString *password = self.password.text;
    if([Utils isBlankString:phoneCode]){
        [DialogUtils showTipsWithView:self.view String:@"手机号不能为空"];
        return;
    }
    if([Utils isBlankString:validCode]){
        [DialogUtils showTipsWithView:self.view String:@"验证码不能为空"];
        return;
    }
    if([Utils isBlankString:password]){
        [DialogUtils showTipsWithView:self.view String:@"密码不能为空"];
        return;
    }
    MBProgressHUD *loding = [DialogUtils showLoadingWithView:self.view];
    JXBaseRequest *request = [[JXBaseRequest alloc]init];
    NSDictionary *dic = [request keyValues];
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:dic];
    [params setObject:phoneCode forKey:@"phoneCode"];
    [params setObject:validCode forKey:@"validateCode"];
    [params setObject:password forKey:@"password"];
    [SelfDataTool resetPwdWithParam:params success:^(JXBaseResponse *result) {
        [loding hide:YES];
        if([Utils isBlankString:[result data]]){//重设密码成功
            [DialogUtils showTipsWithView:self.view String:@"重设密码成功"];
            JXLog(@"重设密码成功");
            [self.navigationController popViewControllerAnimated:YES];
            JXNavigationController *nav = [[JXNavigationController alloc]initWithRootViewController:[[JXLoginController alloc]init]];
            [self presentViewController:nav animated:true completion:^{
            }];
        }else{//发送验证码失败
            [DialogUtils showTipsWithView:self.view String:@"重设密码失败"];
            JXLog(@"重设密码失败:%@",[result data]);
        }
    } failure:^(NSError *error) {
        [loding hide:YES];
         [DialogUtils showTipsWithView:self.view String:@"重设密码失败"];
        JXLog(@"failure重设密码失败:%@",error);
    }];
}

- (void)startCountDown {
    //处理倒计时
    NSString* time_str = [NSString stringWithFormat:@"倒计时%d秒",time];
    _countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:_countDownTimer forMode:NSDefaultRunLoopMode];
    [_sendCodeBtn setEnabled:NO];
    [_sendCodeBtn setBackgroundImage:nil forState:UIControlStateNormal];
    [_sendCodeBtn setBackgroundImage:[UIImage resizedImage:@"send_code_disable_bg"] forState:UIControlStateDisabled];
    [_sendCodeBtn setTitle:time_str forState:UIControlStateDisabled];
}

/**
 *  发送验证码
 */
-(void) sendCode{
    NSString *phoneCode = self.phoneCode.text;
    if(![Utils isBlankString:phoneCode]){
        MBProgressHUD *loding = [DialogUtils showLoadingWithView:self.view];
        JXBaseRequest *request = [[JXBaseRequest alloc]init];
        NSDictionary *dic = [request keyValues];
        NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:dic];
        [params setObject:phoneCode forKey:@"phoneCode"];
        [SelfDataTool sendCodeWithParam:params success:^(JXBaseResponse *result) {
            //处理倒计时
            [self startCountDown];
            [loding hide:YES];
            if([Utils isBlankString:[result data]]){//发送验证码成功
                [DialogUtils showTipsWithView:self.view String:@"发送成功"];
                JXLog(@"发送验证码成功");
            }else{//发送验证码失败
                [DialogUtils showTipsWithView:self.view String:@"发送失败"];
                JXLog(@"发送验证码失败:%@",[result data]);
            }
        } failure:^(NSError *error) {
             [loding hide:YES];
             [DialogUtils showTipsWithView:self.view String:@"发送失败"];
            JXLog(@"failure发送验证码失败:%@",error);
        }];
    }else{
        [DialogUtils showTipsWithView:self.view String:@"手机号不能位空"];
    }
}

/**
 *  倒计时调用的方法
 */
-(void)timeFireMethod{
    if(time <= 0){
        [_countDownTimer invalidate];
        [_sendCodeBtn setBackgroundImage:nil forState:UIControlStateNormal];
        [_sendCodeBtn setBackgroundImage:[UIImage resizedImage:@"btn_login_bg"] forState:UIControlStateNormal];
        [_sendCodeBtn setEnabled:YES];
        [_sendCodeBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
    }else{
        time--;
        NSString *timeStr = [NSString stringWithFormat:@"倒计时%d秒",time];
        [_sendCodeBtn setTitle:timeStr forState:UIControlStateDisabled];
    }
}

@end
